package com.pzhu.dormitory.controller;


import com.pzhu.dormitory.entity.StudentEntity;
import com.pzhu.dormitory.entity.UserEntity;
import com.pzhu.dormitory.entity.UserRoleRelationEntity;
import com.pzhu.dormitory.service.StudentService;
import com.pzhu.dormitory.service.UserRoleRelationService;
import com.pzhu.dormitory.service.UserService;
import com.pzhu.dormitory.utils.PageUtils;
import com.pzhu.dormitory.utils.R;
import com.pzhu.dormitory.utils.Rb;
import com.pzhu.dormitory.vo.ChangePasswordVo;
import com.pzhu.dormitory.vo.RegisterVo;
import com.pzhu.dormitory.vo.UserRoleVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Map;
import java.util.Optional;


/**
 * 后台用户表
 *
 * @author
 * @email
 * @date 2021-04-10 08:46:25
 */
@Slf4j
@RestController
@Api(value = "UserController", tags = "后台用户表")
@RequestMapping("elective/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserRoleRelationService userRoleRelationService;

    @Autowired
    private StudentService studentService;


    /**
     * 删除
     */
    @ApiOperation(value = "注册")
    @PostMapping("/register")
    @Transactional
    public R<UserEntity> register(@RequestBody RegisterVo registerVo) {
        UserEntity one = userService.lambdaQuery().eq(UserEntity::getUsername, registerVo.getUsername())
                .one();
        if (one != null) {
            throw new RuntimeException("用户已存在");
        }
        UserEntity userEntity = new UserEntity();
        userEntity.setUsername(registerVo.getUsername());
        userEntity.setPassword(passwordEncoder.encode(registerVo.getPassword()));
        userService.save(userEntity);
        UserRoleRelationEntity userRoleRelationEntity = new UserRoleRelationEntity();
        userRoleRelationEntity.setUserId(userEntity.getId());
        if ("1".equals(registerVo.getType())) {
            // 创建医生
            StudentEntity  studentEntity = new StudentEntity();
            BeanUtils.copyProperties(registerVo, studentEntity);
            studentEntity.setSno(userEntity.getUsername());
            studentEntity.setId(null);
            // 更新权限
            userRoleRelationEntity.setRoleId(3L);

        }
        userRoleRelationService.saveOrUpdate(userRoleRelationEntity);
        return Rb.a(UserEntity.class).success().build();
    }

    /**
     * 列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "获取后台用户表list")
    public R<UserEntity> list(@RequestParam Map<String, Object> params) {
        PageUtils<UserEntity> page = userService.queryPage(params);
        return Rb.a(UserEntity.class).success().page(page).build();
    }


    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    @ApiOperation(value = "获取一个后台用户表信息")
    public R<UserEntity> info(@Validated @PathVariable("id") Long id) {
        UserEntity user = userService.getById(id);
        return Rb.a(UserEntity.class).success().withData(user).build();
    }

    /**
     * 保存
     */
    @ApiOperation(value = "保存后台用户表信息")
    @PostMapping("/save")
    public R<UserEntity> save(@Validated @RequestBody UserEntity user) {
        UserEntity one = userService.lambdaQuery().eq(UserEntity::getUsername, user.getUsername()).one();
        if (one != null) {
            throw new RuntimeException("用户已存在");
        }
        if (StringUtils.isNoneBlank(user.getPassword())) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        } else {
            user.setPassword(null);
        }
        userService.save(user);
        return Rb.a(UserEntity.class).success().build();
    }

    /**
     * 修改
     */
    @ApiOperation(value = "更新后台用户表信息")
    @PutMapping("/update")
    public R<UserEntity> update(@RequestBody UserEntity user) {
        UserEntity one = userService.lambdaQuery().eq(UserEntity::getUsername, user.getUsername())
                .ne(UserEntity::getId, user.getId())
                .one();
        if (one != null) {
            throw new RuntimeException("用户已存在");
        }
        if (StringUtils.isNoneBlank(user.getPassword())) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        } else {
            user.setPassword(null);
        }
        userService.updateById(user);
        return Rb.a(UserEntity.class).success().build();
    }

    /**
     * 删除
     */
    @ApiOperation(value = "删除后台用户表信息")
    @DeleteMapping("/delete")
    public R<UserEntity> delete(@RequestBody Long[] ids) {
        userService.removeByIds(Arrays.asList(ids));
        return Rb.a(UserEntity.class).success().build();
    }

    /**
     * 查询用户角色
     */
    @ApiOperation(value = "查询用户角色")
    @GetMapping("/role/{userId}")
    public R<UserRoleVo> roles(@PathVariable String userId) {
        UserRoleVo userRoleVo = userService.loadRoles(userId);
        return Rb.a(UserRoleVo.class).success().withData(userRoleVo).build();
    }


    /**
     * 修改
     */
    @ApiOperation(value = "更新密码")
    @PutMapping("/update/password")
    public R<UserEntity> updatePassword(@RequestBody ChangePasswordVo changePasswordVo) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Optional<UserEntity> entityOptional = userService.lambdaQuery().eq(UserEntity::getUsername, authentication.getName()).oneOpt();
        entityOptional.ifPresent(userEntity -> {
            String encodeOld = passwordEncoder.encode(changePasswordVo.getOldPwd());
            if (encodeOld.equals(userEntity.getPassword())) {
                userEntity.setPassword(passwordEncoder.encode(changePasswordVo.getNewPwd()));
                userService.updateById(userEntity);
            } else {
                throw new RuntimeException("旧密码错误");
            }
        });
        return Rb.a(UserEntity.class).success().build();
    }

}
